import { sysCodeCache } from '@/utils/sysCode'

const JsonSysCode = sysCodeCache || {}

const codeNameKey = 'code_name'
const codeValueKey = 'code_value'

export default function get(key) {
  if (JsonSysCode.hasOwnProperty(key)) {
    return JsonSysCode[key]
  } else {
    return null
  }
}
export const V2N = function(key, value) {
  const d = get(key)
  const l = d && d.length
  for (let i = 0; i < l; i++) {
    if (d[i][codeValueKey] === value || d[i][codeValueKey] === `${value}`) {
      return d[i][codeNameKey]
    }
  }
  return null
}
const _funType = get('FUN_TYPE')
const _funTypeVN = Object.prototype.toString.call(_funType) === "[object Array]" && _funType.map(item => item[codeNameKey])
export const funType = function(key) {
  return _funTypeVN ? _funTypeVN[parseInt(key)] : ''
}

export function getCodeName(val, dataType) {
  const codeData = get(dataType)
  const valType = typeof val
  if (codeData && codeData.length) {
    const filter = codeData.filter((item) => {
      if (valType === 'number') {
        return parseInt(item[codeValueKey]) === val
      } else if (valType === 'string') {
        return item[codeValueKey] === val
      }
    })
    if (filter && filter.length) {
      return filter[0][codeNameKey]
    } else {
      return ''
    }
  }
}

export function getCodeValue(val, dataType) {
  const codeData = get(dataType)
  if (val && val.length) {
    if (codeData && codeData.length) {
      const filter = codeData.filter((item) => {
        return item[codeNameKey] === val
      })
      if (filter && filter.length) {
        return filter[0][codeValueKey]
      } else {
        return ''
      }
    }
  }
}
